https://laihao2.com/Home/WaterCreate
ASP.NET開發操作流程:資料表設定好>再寫程式:加入資料庫>串聯資料庫>產生Models裡面類別檔dao>按:建置>Controllers裡面的Entities>產生畫面View
資料表設定好>再寫程式:加入資料庫>串聯資料庫>
參考昨天部分~
產生Models裡面類別檔dao>按:建置>
參考昨天部分~
Controllers裡面的Entities>
public ActionResult WaterCreate()
        {
            ViewBag.Layout = "~/Views/Shared/_Layout.cshtml";
            return View();
        }
        //[AllowAnonymous]
        [HttpPost]
        //public ActionResult WaterCreate(WATER_BILL customer)
        //20240322新增PDF上傳
        public ActionResult WaterCreate(WATER_BILL customer, HttpPostedFileBase pdfFile)
        {
            //20240424文件大小超過 3MB跳出提示
            if (pdfFile != null && pdfFile.ContentLength > 3 * 1024 * 1024)
            {
                // 文件大小超過 3MB
                //ModelState.AddModelError("pdfFile", "上傳的 PDF 文件大小不能超過 2MB。");
                // 將錯誤訊息添加到 TempData,以便在視圖中顯示
                TempData["ErrorMessage"] = "上傳的 PDF 文件大小不能超過 3MB。";
                return View(customer);
            }
            if (ModelState.IsValid)
            {
                string custId = customer.DOCUMENT_ID;
                var temp = _db.WATER_BILL
                    .Where(m => m.DOCUMENT_ID == custId)
                    .FirstOrDefault();
                if (temp == null)
                {
                    // HomeController_20231226紀錄登打時間
                    //customer.data = DateTime.Now;
                    // 從 Session 讀取當前登錄用戶
                    //var username = Session["Member"] as tMember;
                    // 將當前登錄用戶賦值給 CreatedBy 屬性
                    //customer.CreatedBy = username.fUserId;
                    // 上傳PDF 檔案
                    if (pdfFile != null && pdfFile.ContentLength > 0)
                    {
                        // 讀取上傳的 PDF 檔案內容
                        var pdfContent = new byte[pdfFile.ContentLength];
                        pdfFile.InputStream.Read(pdfContent, 0, pdfFile.ContentLength);
                        // 將 PDF 檔案內容保存到模型中
                        customer.PDF_CONTENT = pdfContent;
                    }
                    _db.WATER_BILL.Add(customer);
                    _db.SaveChanges();  // 保存更改到資料庫
                    return RedirectToAction("WaterList");
                }
                ViewBag.Msg = "單據號碼重複";
            }
            // 如果模型驗證失敗,返回 View 以顯示錯誤消息
            return View(customer);
        }
解釋程式碼
這段代碼是一個 ASP.NET MVC 控制器方法,負責處理一個叫做 WaterCreate 的表單提交。它涉及創建一個 WATER_BILL 實體對象並上傳 PDF 文件。下面是詳細解釋:
public ActionResult WaterCreate()GET 方法,用於顯示創建 WATER_BILL 的視圖。ViewBag.Layout 為共享布局 _Layout.cshtml,然後返回視圖(表單頁面)。public ActionResult WaterCreate(WATER_BILL customer, HttpPostedFileBase pdfFile)POST 方法,接收表單中的 WATER_BILL 對象 (customer) 和上傳的 PDF 文件 (pdfFile)。WATER_BILL customer: 表單中用戶填寫的 WATER_BILL 數據。HttpPostedFileBase pdfFile: 用戶上傳的 PDF 文件。if (pdfFile != null && pdfFile.ContentLength > 3 * 1024 * 1024)
{
    TempData["ErrorMessage"] = "上傳的 PDF 文件大小不能超過 3MB。";
    return View(customer);
}
TempData 添加錯誤消息,返回視圖以顯示錯誤。ModelState.IsValidDOCUMENT_IDvar temp = _db.WATER_BILL
    .Where(m => m.DOCUMENT_ID == custId)
    .FirstOrDefault();
if (temp == null)
{
DOCUMENT_ID 在數據庫中查找是否已有該記錄。DOCUMENT_ID,即記錄不重覆,則繼續執行記錄創建流程。CreatedBy 屬性以記錄創建者信息。if (pdfFile != null && pdfFile.ContentLength > 0)
{
    var pdfContent = new byte[pdfFile.ContentLength];
    pdfFile.InputStream.Read(pdfContent, 0, pdfFile.ContentLength);
    customer.PDF_CONTENT = pdfContent;
}
WATER_BILL 模型中的 PDF_CONTENT 屬性。_db.WATER_BILL.Add(customer);
_db.SaveChanges();
WATER_BILL 對象添加到數據庫,並保存更改。WaterListWaterList 列表頁面。ViewBag.Msg = "單據號碼重複";
DOCUMENT_ID 重覆,則在視圖中顯示錯誤消息。WATER_BILL 表中,並重定向到列表頁面;如果失敗,則返回視圖並顯示錯誤信息。產生畫面View程式碼
@*@model IEnumerable<WebApplication5.Models.WATER_BILL>*@
@model WebApplication5.Models.WATER_BILL
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
    ViewBag.Title = "WaterCreate";
}
<style>
    .align-right {
        text-align: right;
    }
    .nowrap {
        white-space: nowrap;
    }
</style>
<h2>新增</h2>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        // 當FACTORY字段的值更改時
        $("#FACTORY").change(function () {
            // 獲取所選的FACTORY值
            var FACTORY = $(this).val();
            // 根據FACTORY的值設置相應的ELECTRICITY_SIGNAL選項
            if (FACTORY === "永科廠") {
                $("#WATER_SIGNAL").val("23-45678901-2");
                $("#METER_NUMBER").val("123D456780");
                $("#METER_DIAMETER").val("75");
            } else if (FACTORY === "永康廠") {
                $("#WATER_SIGNAL").val("12-34567890-1");
                $("#METER_NUMBER").val("123D456789");
                $("#METER_DIAMETER").val("40");
            }
            @*else if (FACTORY === "樹谷二期") {
                $("#WATER_SIGNAL").val("63-43233503-8");
                $("#METER_NUMBER").val("103G000227");
                $("#METER_DIAMETER").val("100");
            }*@
        });
    });
</script>
<script>
    $(document).ready(function () {
        // 為數字輸入框添加格式化事件
        $(".numeric-input").on("input", function () {
            formatNumberInput($(this));
        });
        // 提交表單時移除千位分隔符
        $("form").submit(function () {
            $(".numeric-input").each(function () {
                $(this).val($(this).val().replace(/,/g, ''));
            });
        });
    });
    // 格式化數字輸入框的值
    /*function formatNumberInput(input) {
        var val = input.val().replace(/,/g, ''); // 移除現有的千位分隔符
        if (val != '') {
            val = parseInt(val); // 確保輸入是一個數值
            input.val(val.toLocaleString()); // 使用toLocaleString()添加千位分隔符
        }
    }*/
    // 格式化數字輸入框的值
    function formatNumberInput(input) {
        var val = input.val().replace(/,/g, ''); // 移除現有的千位分隔符
        if (val != '') {
            var parts = val.split('.'); // 將輸入值拆分為整數部分和小數部分
            parts[0] = parseInt(parts[0]).toLocaleString(); // 格式化整數部分
            input.val(parts.join('.')); // 重新組合並設置輸入框的值
        }
    }
</script>
@*20240424增加上傳檔案超過3MB提示 *@
<script>
    $(document).ready(function () {
        $('form').submit(function () {
            var file = $('.pic-upload-input')[0].files[0];
            if (file && file.size > 3 * 1024 * 1024) {
                alert('上傳的 PDF 文件大小不能超過 2MB。');
                return false; // 防止表單提交
            }
        });
    });
</script>
@if (ViewBag.Msg != null)
{
    <div class="alert alert-danger">@ViewBag.Msg</div>
}
@*20240325增加上傳檔案 *@
@*@using (Html.BeginForm()) *@
@using (Html.BeginForm("WaterCreate", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <div class="form-inline">
        <h4>水費帳單</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.DOCUMENT_ID, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.DOCUMENT_ID, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DOCUMENT_ID, "", new { @class = "text-danger" })
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.FACTORY, htmlAttributes: new { @class = "control-label" })
            @{
                var listItemsFACTORY = new List<SelectListItem>
{
                    new SelectListItem { Text = "永康廠", Value = "永康廠", Selected = true },
                    @*new SelectListItem { Text = "樹谷一期", Value = "樹谷一期", Selected = true },*@
                    new SelectListItem { Text = "永科廠", Value = "永科廠" }
                };
            }
            @Html.DropDownList("FACTORY", listItemsFACTORY, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.FACTORY, "", new { @class = "text-danger" })
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.WATER_SIGNAL, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.WATER_SIGNAL, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
            @Html.ValidationMessageFor(model => model.WATER_SIGNAL, "", new { @class = "text-danger" })
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.FROM_BILLING_PERIOD, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.FROM_BILLING_PERIOD, new { htmlAttributes = new { @class = "form-control", type = "date" } })
            @Html.ValidationMessageFor(model => model.FROM_BILLING_PERIOD, "", new { @class = "text-danger" })
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.UNTIL_BILLING_PERIOD, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.UNTIL_BILLING_PERIOD, new { htmlAttributes = new { @class = "form-control", type = "date" } })
            @Html.ValidationMessageFor(model => model.UNTIL_BILLING_PERIOD, "", new { @class = "text-danger" })
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.TYPE, htmlAttributes: new { @class = "control-label" })
            @{
                var listItemsTYPE = new List<SelectListItem>
{
                    new SelectListItem { Text = "普通", Value = "普通", Selected = true },
                    new SelectListItem { Text = "工業", Value = "工業" }
                };
            }
            @Html.DropDownList("TYPE", listItemsTYPE, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.TYPE, "", new { @class = "text-danger" })
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.METER_NUMBER, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.METER_NUMBER, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
            @Html.ValidationMessageFor(model => model.METER_NUMBER, "", new { @class = "text-danger" })
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.METER_DIAMETER, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.METER_DIAMETER, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
            @Html.ValidationMessageFor(model => model.METER_DIAMETER, "", new { @class = "text-danger" })
        </div>
        @*<div class="form-group">
                @Html.LabelFor(model => model.NUMBER_POINTERS, htmlAttributes: new { @class = "control-label" })
                @Html.EditorFor(model => model.NUMBER_POINTERS, new { htmlAttributes = new { @class = "form-control  align-right" } })
                @Html.ValidationMessageFor(model => model.NUMBER_POINTERS, "", new { @class = "text-danger" })
            </div>*@
        @*20240327在框中顯示千位分隔符號(例如"1,000")的格式*@
        <div class="form-group">
            @Html.LabelFor(model => model.NUMBER_POINTERS, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.NUMBER_POINTERS, new { htmlAttributes = new { @class = "form-control numeric-input align-right" } })
            @Html.ValidationMessageFor(model => model.NUMBER_POINTERS, "", new { @class = "text-danger" })
        </div>
        @*<div class="form-group">
                @Html.LabelFor(model => model.TOTAL_WATER, htmlAttributes: new { @class = "control-label" })
                @Html.EditorFor(model => model.TOTAL_WATER, new { htmlAttributes = new { @class = "form-control  align-right" } })
                @Html.ValidationMessageFor(model => model.TOTAL_WATER, "", new { @class = "text-danger" })
            </div>*@
        @*20240327在框中顯示千位分隔符號(例如"1,000")的格式*@
        <div class="form-group">
            @Html.LabelFor(model => model.TOTAL_WATER, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.TOTAL_WATER, new { htmlAttributes = new { @class = "form-control numeric-input align-right" } })
            @Html.ValidationMessageFor(model => model.TOTAL_WATER, "", new { @class = "text-danger" })
        </div>
        @*<div class="form-group">
                @Html.LabelFor(model => model.TOTAL_BILL_TAX, htmlAttributes: new { @class = "control-label" })
                @Html.EditorFor(model => model.TOTAL_BILL_TAX, new { htmlAttributes = new { @class = "form-control  align-right" } })
                @Html.ValidationMessageFor(model => model.TOTAL_BILL_TAX, "", new { @class = "text-danger" })
            </div>*@
        @*20240327在框中顯示千位分隔符號(例如"1,000")的格式*@
        <div class="form-group">
            @Html.LabelFor(model => model.TOTAL_BILL_TAX, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.TOTAL_BILL_TAX, new { htmlAttributes = new { @class = "form-control numeric-input align-right" } })
            @Html.ValidationMessageFor(model => model.TOTAL_BILL_TAX, "", new { @class = "text-danger" })
        </div>
        @*<div class="form-group">
                @Html.LabelFor(model => model.CARBON_PERIOD, htmlAttributes: new { @class = "control-label" })
                @Html.EditorFor(model => model.CARBON_PERIOD, new { htmlAttributes = new { @class = "form-control  align-right" } })
                @Html.ValidationMessageFor(model => model.CARBON_PERIOD, "", new { @class = "text-danger" })
            </div>*@
        @*20240327在框中顯示千位分隔符號(例如"1,000")的格式*@
        <div class="form-group">
            @Html.LabelFor(model => model.CARBON_PERIOD, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.CARBON_PERIOD, new { htmlAttributes = new { @class = "form-control numeric-input align-right" } })
            @Html.ValidationMessageFor(model => model.CARBON_PERIOD, "", new { @class = "text-danger" })
        </div>
        @*<div class="form-group">
                @Html.LabelFor(model => model.CARBON_EMISSION_FACTOR, htmlAttributes: new { @class = "control-label" })
                @Html.EditorFor(model => model.CARBON_EMISSION_FACTOR, new { htmlAttributes = new { @class = "form-control  align-right" } })
                @Html.ValidationMessageFor(model => model.CARBON_EMISSION_FACTOR, "", new { @class = "text-danger" })
            </div>*@
        @*20240327在框中顯示千位分隔符號(例如"1,000")的格式*@
        <div class="form-group">
            @Html.LabelFor(model => model.CARBON_EMISSION_FACTOR, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.CARBON_EMISSION_FACTOR, new { htmlAttributes = new { @class = "form-control numeric-input align-right" } })
            @Html.ValidationMessageFor(model => model.CARBON_EMISSION_FACTOR, "", new { @class = "text-danger" })
        </div>
        @*<div class="form-group">
                @Html.LabelFor(model => model.CARBON_DIOXIDE, htmlAttributes: new { @class = "control-label" })
                @Html.EditorFor(model => model.CARBON_DIOXIDE, new { htmlAttributes = new { @class = "form-control  align-right" } })
                @Html.ValidationMessageFor(model => model.CARBON_DIOXIDE, "", new { @class = "text-danger" })
            </div>*@
        @*20240327在框中顯示千位分隔符號(例如"1,000")的格式*@
        <div class="form-group">
            @Html.LabelFor(model => model.CARBON_DIOXIDE, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.CARBON_DIOXIDE, new { htmlAttributes = new { @class = "form-control numeric-input align-right" } })
            @Html.ValidationMessageFor(model => model.CARBON_DIOXIDE, "", new { @class = "text-danger" })
        </div>
        <!-- **** 20240327加入輸入傳票號碼**** -->
        <div class="form-group">
            @Html.LabelFor(model => model.VOUCHER_NUMBER, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.VOUCHER_NUMBER, new { htmlAttributes = new { @class = "form-control  align-right" } })
            @Html.ValidationMessageFor(model => model.VOUCHER_NUMBER, "", new { @class = "text-danger" })
        </div>
        <div>
            <span class="editor-label">
                @Html.LabelFor(model => model.PDF_FILE):
            </span>
            <span class="editor-field">
                <!-- **** 檔案上傳 **** -->
                <input class="pic-upload-input" type="file" name="pdfFile">
                <!-- **** 檔案上傳 **** -->
            </span>
        </div>
        @*<div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="存檔" class="btn btn-danger" />
                </div>
            </div>*@
        <!-- 添加一個空div來留出空白 -->
        <div style="height: 50px;"></div>
        <div class="text-center">
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="存檔" class="btn btn-danger" />
                </div>
            </div>
        </div>
    </div>
}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
解釋程式碼
這段程式碼是一個 ASP.NET MVC 的 Razor 視圖,用於顯示 "新增水費帳單" 的表單。以下是程式碼的詳細解釋:
@model WebApplication5.Models.WATER_BILL
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "WaterCreate";
}
@model 指定了該視圖的模型為 WebApplication5.Models.WATER_BILL,表示表單將操作一個 WATER_BILL 類型的物件。Layout = "~/Views/Shared/_Layout.cshtml" 設置了該視圖使用的佈局頁。ViewBag.Title 設置了該頁面的標題。<style>
    .align-right {
        text-align: right;
    }
    .nowrap {
        white-space: nowrap;
    }
</style>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#FACTORY").change(function () {
            var FACTORY = $(this).val();
            if (FACTORY === "永科廠") {
                $("#WATER_SIGNAL").val("23-45678901-2");
                $("#METER_NUMBER").val("123D456780");
                $("#METER_DIAMETER").val("75");
            } else if (FACTORY === "永康廠") {
                $("#WATER_SIGNAL").val("12-34567890-1");
                $("#METER_NUMBER").val("123D456789");
                $("#METER_DIAMETER").val("40");
            }
        });
    });
</script>
FACTORY) 欄位的值改變時,自動填充一些對應的水號 (WATER_SIGNAL)、水表號 (METER_NUMBER) 和水表直徑 (METER_DIAMETER) 值。<script>
    $(document).ready(function () {
        $(".numeric-input").on("input", function () {
            formatNumberInput($(this));
        });
        $("form").submit(function () {
            $(".numeric-input").each(function () {
                $(this).val($(this).val().replace(/,/g, ''));
            });
        });
    });
    function formatNumberInput(input) {
        var val = input.val().replace(/,/g, '');
        if (val != '') {
            var parts = val.split('.');
            parts[0] = parseInt(parts[0]).toLocaleString();
            input.val(parts.join('.'));
        }
    }
</script>
.numeric-input) 增加了千位分隔符的格式化功能,並確保在提交表單時去除千位分隔符以避免數據處理錯誤。<script>
    $(document).ready(function () {
        $('form').submit(function () {
            var file = $('.pic-upload-input')[0].files[0];
            if (file && file.size > 3 * 1024 * 1024) {
                alert('上傳的 PDF 文件大小不能超過 3MB。');
                return false;
            }
        });
    });
</script>
@using (Html.BeginForm("WaterCreate", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <div class="form-inline">
        <h4>水費帳單</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        
        <!-- 文件上傳區域 -->
        <div class="form-group">
            <span class="editor-label">
                @Html.LabelFor(model => model.PDF_FILE):
            </span>
            <span class="editor-field">
                <input class="pic-upload-input" type="file" name="pdfFile">
            </span>
        </div>
        <!-- 其他輸入字段 -->
        <div class="form-group">
            @Html.LabelFor(model => model.DOCUMENT_ID, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.DOCUMENT_ID, new { htmlAttributes = new { @class = "form-control" } })
        </div>
        <!-- 數字輸入框,包含千位分隔符格式化 -->
        <div class="form-group">
            @Html.LabelFor(model => model.TOTAL_WATER, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.TOTAL_WATER, new { htmlAttributes = new { @class = "form-control numeric-input align-right" } })
        </div>
        
        <!-- 表單提交按鈕 -->
        <div class="text-center">
            <div class="form-group">
                <input type="submit" value="存檔" class="btn btn-danger" />
            </div>
        </div>
    </div>
}
Html.BeginForm() 生成表單,enctype 設置為 multipart/form-data 允許文件上傳。Html.EditorFor() 生成對應的輸入框,並伴隨相應的驗證信息 (ValidationMessageFor)。@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Scripts.Render("~/bundles/jqueryval") 用於包含 jQuery 驗證腳本,確保表單驗證功能正常工作。這段程式碼用於顯示一個用戶介面的表單,讓用戶可以提交水費帳單信息。表單包括文件上傳、動態選項填充、數字輸入格式化等功能,並且內建了表單驗證與錯誤處理。
大家明天見~